import React, { useEffect, useState, useCallback, useMemo, lazy, Suspense } from 'react';
import { Card, Row, Col, Pagination, Spin, Empty, message, Tabs, Badge } from 'antd';
import { FireOutlined, LoadingOutlined, WeiboOutlined, ReadOutlined, CustomerServiceOutlined, PlaySquareOutlined, BulbOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { HotItemCard } from '../../components/hotRadar/HotItemCard';
import { HotItemCardSkeleton } from '../../components/hotRadar/HotItemCard/HotItemCardSkeleton';
import { FilterPanel } from '../../components/hotRadar/FilterPanel';
import { useHotRadarStore } from '../../stores/hotRadar.store';
import { useModelConfigStore } from '../../stores/model-config.store';
import { hotRadarService } from '../../services/hotRadar.service';
import { HotItemBase } from '../../types/hotRadar';
import { debounce } from '../../utils/throttle';
import ErrorBoundary from '../../components/common/ErrorBoundary';
import { useBreakpoint } from '../../hooks/useBreakpoint';
import { Container } from '../../components/Responsive/ResponsiveExports';
import { usePullToRefresh } from '../../hooks/usePullToRefresh';
import { useInfiniteScroll } from '../../hooks/useInfiniteScroll';
import BottomNavigation from '../../components/navigation/BottomNavigation';
import './style.css';

// 懒加载HotCreatorModal - 只在需要时加载
const HotCreatorModal = lazy(() => import('../../components/hotRadar/HotItemDetailModal/HotCreatorModal'));

const HotRadar: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [selectedItem, setSelectedItem] = useState<HotItemBase | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [defaultTab, setDefaultTab] = useState<string>('detail'); // 新增：控制默认打开的tab
  const [platformsData, setPlatformsData] = useState<Record<string, HotItemBase[]>>({});
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const breakpoint = useBreakpoint();
  const isMobile = breakpoint === 'mobile';

  const {
    filters,
    setFilters,
  } = useHotRadarStore();

  const { loadConfigs } = useModelConfigStore();

  // 预加载模型配置 - 页面加载时就开始加载，不等用户点击
  useEffect(() => {
    console.log('🚀 [HotRadar] 预加载模型配置...');
    loadConfigs().catch(err => {
      console.error('❌ [HotRadar] 模型配置预加载失败:', err);
    });
  }, []); // 只执行一次

  // Fetch hot items data with debouncing for filter changes
  const fetchHotItems = useCallback(async (page = 1, append = false) => {
    console.log('🚀 [HotRadar] fetchHotItems called:', { page, append, filters });
    setLoading(true);
    try {
      console.log('📡 [HotRadar] Calling API with params:', {
        page,
        page_size: 20,
        platforms: filters.platforms,
        time_range: filters.timeRange,
      });
      const response = await hotRadarService.getHotItems({
        page,
        page_size: 20, // 分页加载
        platforms: filters.platforms,
        time_range: filters.timeRange,
      });
      
      // 处理新的数据格式 - 按平台分组
      console.log('🔍 Processing response data:', {
        success: response.success,
        dataType: typeof response.data,
        isArray: Array.isArray(response.data),
        dataKeys: response.data ? Object.keys(response.data) : 'no data',
        data: response.data
      });
      
      if (response.success && response.data) {
        // 检查是否是新的平台分组格式
        if (typeof response.data === 'object' && !Array.isArray(response.data)) {
          // 新格式：{ platforms: {...} } 或者直接是平台对象 {...}
          const platforms = response.data.platforms || response.data;
          console.log('📊 Setting platforms data:', platforms);

          if (append) {
            // 追加数据
            setPlatformsData((prev) => {
              const merged: Record<string, HotItemBase[]> = { ...prev };
              Object.keys(platforms).forEach((platform) => {
                merged[platform] = [...(merged[platform] || []), ...platforms[platform]];
              });
              return merged;
            });
          } else {
            setPlatformsData(platforms);
          }

          // 检查是否还有更多数据
          const totalItems = Object.values(platforms).reduce((sum, items) => sum + items.length, 0);
          setHasMore(totalItems >= 20); // 如果返回数据少于page_size，说明没有更多了
        } else if (Array.isArray(response.data)) {
          // 兼容旧格式 - 数组
          console.log('📋 Processing array data:', response.data.length, 'items');
          const items = response.data as HotItemBase[];
          const groupedData: Record<string, HotItemBase[]> = {};
          items.forEach((item: HotItemBase) => {
            if (!groupedData[item.platform]) {
              groupedData[item.platform] = [];
            }
            groupedData[item.platform].push(item);
          });

          if (append) {
            setPlatformsData((prev) => {
              const merged: Record<string, HotItemBase[]> = { ...prev };
              Object.keys(groupedData).forEach((platform) => {
                merged[platform] = [...(merged[platform] || []), ...groupedData[platform]];
              });
              return merged;
            });
          } else {
            setPlatformsData(groupedData);
          }

          setHasMore(items.length >= 20);
        }
      }
    } catch (error) {
      const errorMessage = '获取热点数据失败，请稍后重试';
      setError(errorMessage);
      message.error(errorMessage);
      console.error('Failed to fetch hot items:', error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  // Debounce filter changes to prevent excessive API calls
  const debouncedFetchHotItems = useMemo(
    () => debounce(fetchHotItems, 500),
    [fetchHotItems]
  );

  useEffect(() => {
    debouncedFetchHotItems();
  }, [debouncedFetchHotItems]);

  const handleItemClick = (item: HotItemBase) => {
    setSelectedItem(item);
    setDetailModalVisible(true);
  };

  const handleDetailModalClose = () => {
    setDetailModalVisible(false);
    setSelectedItem(null);
  };

  const handleViewItem = (item: HotItemBase) => {
    setSelectedItem(item);
    setDefaultTab('detail'); // 查看详情
    setDetailModalVisible(true);
  };

  const handleCreateContent = (item: HotItemBase) => {
    // 打开创作模态框而不是跳转到编辑器页面
    console.log('创作内容基于:', item.title);
    setSelectedItem(item);
    setDefaultTab('create'); // 直接进入创作tab
    setDetailModalVisible(true);
  };

  // 新增：头脑风暴创作
  const handleBrainstorm = (item: HotItemBase) => {
    console.log('头脑风暴创作基于:', item.title);
    // 跳转到创作工坊，传递热点信息
    navigate(`/brainstorm/workshop?hotTopicId=${item.item_id}&hotTopicTitle=${encodeURIComponent(item.title)}`);
  };

  const handleClearFilters = () => {
    setFilters({
      platforms: [],
      timeRange: '24h',
    });
  };

  // 下拉刷新
  const handleRefresh = useCallback(async () => {
    setCurrentPage(1);
    setError(null);
    await fetchHotItems(1, false);
    message.success('刷新成功');
  }, [fetchHotItems]);

  // 加载更多
  const handleLoadMore = useCallback(async () => {
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    await fetchHotItems(nextPage, true);
  }, [currentPage, fetchHotItems]);

  // 移动端下拉刷新
  const { pulling, refreshing, pullDistance } = usePullToRefresh({
    onRefresh: handleRefresh,
    threshold: 80,
    disabled: !isMobile,
  });

  // 移动端无限滚动
  const { loading: loadingMore } = useInfiniteScroll({
    onLoadMore: handleLoadMore,
    hasMore,
    threshold: 200,
    disabled: !isMobile,
  });

  // 获取平台名称的中文映射
  const platformNames: Record<string, string> = {
    'weibo': '微博',
    'zhihu': '知乎',
    'douyin': '抖音',
    'bilibili': 'B站',
    'toutiao': '头条',
    'baidu': '百度',
    '36kr': '36氪',
    'ithome': 'IT之家',
  };

  // 平台图标组件
  const getPlatformIcon = (platform: string) => {
    const iconProps = { style: { fontSize: '20px' } };
    switch (platform) {
      case 'weibo': return <WeiboOutlined {...iconProps} />;
      case 'zhihu': return <ReadOutlined {...iconProps} />;
      case 'douyin': return <CustomerServiceOutlined {...iconProps} />;
      case 'bilibili': return <PlaySquareOutlined {...iconProps} />;
      default: return <FireOutlined {...iconProps} />;
    }
  };

  return (
    <Container type="responsive">
      <div className="hot-radar-container">
        {/* 下拉刷新指示器 */}
        {isMobile && (pulling || refreshing) && (
          <div
            className="pull-to-refresh-indicator"
            style={{
              height: pullDistance > 0 ? `${pullDistance}px` : '0px',
              opacity: pullDistance / 80,
            }}
          >
            {refreshing ? (
              <>
                <LoadingOutlined spin />
                <span>刷新中...</span>
              </>
            ) : pullDistance > 80 ? (
              <span>释放刷新</span>
            ) : (
              <span>下拉刷新</span>
            )}
          </div>
        )}

        <div className="hot-radar-header">
          <h1>
            <FireOutlined className="header-icon" />
            热点雷达
          </h1>
          <p className="header-subtitle">发现热门话题，把握创作机会</p>
        </div>

        <div className="hot-radar-content">
          {loading && !loadingMore ? (
            <div className="loading-container">
              <Spin size="large" />
            </div>
          ) : error ? (
            <Empty
              description={
                <div>
                  <p>{error}</p>
                  <button
                    className="ant-btn ant-btn-primary"
                    onClick={() => handleRefresh()}
                  >
                    重新加载
                  </button>
                </div>
              }
            />
          ) : Object.keys(platformsData).length === 0 ? (
            <Empty description="暂无热点数据" />
          ) : (
            <>
              {/* 多平台卡片网格布局 */}
              <div className="platforms-grid">
                {Object.entries(platformsData)
                  .filter(([_, items]) => items.length > 0)
                  .map(([platform, items]) => (
                    <Card
                      key={platform}
                      className="platform-card"
                      title={
                        <div className="platform-card-header">
                          {getPlatformIcon(platform)}
                          <span className="platform-name">{platformNames[platform] || platform}</span>
                        </div>
                      }
                      bordered={false}
                    >
                      <div className="platform-items-list">
                        {items.slice(0, 10).map((item, index) => (
                          <div
                            key={item.item_id}
                            className="hot-item-row"
                          >
                            <div className="item-rank">{index + 1}</div>
                            <div className="item-content">
                              <div className="item-title">{item.title}</div>
                              <div className="item-meta">
                                {item.heat_value && item.heat_value !== '0' && (
                                  <span className="item-heat">{item.heat_value}</span>
                                )}
                              </div>
                            </div>
                            <div className="item-actions">
                              <button
                                className="item-action-btn item-action-view"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleViewItem(item);
                                }}
                              >
                                查看
                              </button>
                              <button
                                className="item-action-btn item-action-brainstorm"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleBrainstorm(item);
                                }}
                                title="AI头脑风暴创作"
                              >
                                <BulbOutlined /> 头脑风暴
                              </button>
                              <button
                                className="item-action-btn item-action-create"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleCreateContent(item);
                                }}
                              >
                                创作
                              </button>
                            </div>
                          </div>
                        ))}
                      </div>
                    </Card>
                  ))}
              </div>

              {/* 无限滚动加载指示器 */}
              {isMobile && loadingMore && (
                <div className="infinite-scroll-loading">
                  <Spin indicator={<LoadingOutlined spin />} />
                  <span>加载中...</span>
                </div>
              )}

              {/* 没有更多数据提示 */}
              {isMobile && !hasMore && Object.keys(platformsData).length > 0 && (
                <div className="no-more-data">没有更多数据了</div>
              )}
            </>
          )}
        </div>

        {selectedItem && (
          <Suspense fallback={
            <div style={{
              position: 'fixed',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              background: 'rgba(0, 0, 0, 0.45)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              zIndex: 1000
            }}>
              <div style={{
                background: 'white',
                padding: '24px',
                borderRadius: '8px',
                textAlign: 'center'
              }}>
                <Spin size="large" />
                <div style={{ marginTop: '16px', color: '#666' }}>加载创作工作台...</div>
              </div>
            </div>
          }>
            <HotCreatorModal
              visible={detailModalVisible}
              item={selectedItem}
              defaultTab={defaultTab}
              onClose={handleDetailModalClose}
            />
          </Suspense>
        )}

        {/* 移动端底部导航 */}
        {isMobile && <BottomNavigation activeKey="hot-radar" />}
      </div>
    </Container>
  );
};

export default HotRadar;